<!-- 往来单位--子组建（弹出框） -->
<template>
    <div class="modal-wrapper">
        <a-modal title="新建往来单位" :visible="visible" @ok="handleOk" :okText="'保存'" @cancel="handleCancel" :width="'900px'">
            <a-form :form="form">
                <a-tabs default-active-key="1" @change="callback">
                    <a-tab-pane key="1" tab="基本信息">
                        <a-col :span="12">
                            <a-form-item label="类型" v-bind="formItemLayout">
                                <a-select placeholder="请选择类型" v-decorator="['partnerType',{rules: [{required: true, message: '请选择类型' },]},]">
                                    <a-select-option v-for="(key, index) in partnerType" :key="index" :value="key.type">
                                        {{ key.title }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="单位名称" v-bind="formItemLayout">
                                <a-input allowClear type="text" autocomplete="false" placeholder="请输入单位名称" v-decorator="['crmName',{rules: [{ required: true, message: '请输入单位名称' }],validateTrigger: ['blur']}]"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item v-bind="formItemLayout" label="所属地区">
                                <a-cascader placeholder="请选择所属地区" @change="onAreaChange" :field-names="{label: 'title',value: 'title',children: 'children'}" v-decorator="['areaName',{rules: [{ type: 'array', required: true, message: '请选择所属地区' }]}]" :options="regions" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="首拼码" v-bind="formItemLayout">
                                <a-input allowClear type="text" autocomplete="false" placeholder="请输入单位首拼码" v-model="ruleFormData.crmSimpleName"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item v-bind="formItemLayout" label="信用额度">
                                <a-input type="text" placeholder="请输入信用额度" v-model="ruleFormData.creditLimit"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item v-bind="formItemLayout" label="信用等级">
                                <a-select placeholder="信用等级" v-model="ruleFormData.creditGrade">
                                    <a-select-option v-for="(item, index) in creditRatingArray" :key="index" :value="item.leave">{{ item.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="统一代码" v-bind="formItemLayout">
                                <a-input allowClear type="text" autocomplete="false" placeholder="请输入统一代码" v-model="ruleFormData.companyNumber"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item v-bind="formItemLayout" label="纳税性质">
                                <a-select placeholder="请选择纳税性质" v-model="ruleFormData.taxNature">
                                    <a-select-option v-for="(item, index) in taxNatureList" :key="index" :value="item">{{ item }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="税率%" v-bind="formItemLayout">
                                <a-input allowClear type="number" min="0" max="100" autocomplete="false" placeholder="请输入税率" v-model="ruleFormData.taxRate"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item v-bind="formItemLayout" label="风险等级">
                                <a-select placeholder="请选择风险等级" v-model="ruleFormData.riskLevel">
                                    <a-select-option v-for="(item, index) in riskArray" :key="index" :value="item.leave">{{ item.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>

                    </a-tab-pane>
                    <!--开票信息-->
                    <a-tab-pane key="2" tab="开票信息" force-render>
                        <a-row>
                            <a-col :span="12">
                                <a-form-item label="地址" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="false" placeholder="请输入地址" v-model="ruleFormData.address"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="电话" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" v-model="ruleFormData.phone" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-tab-pane>
                    <!--电子发票接收-->
                    <a-tab-pane key="3" tab="电子发票接收">
                        <a-row>
                            <a-col :span="12">
                                <a-form-item label="电子发票接收邮件" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" v-model="ruleFormData.electronicInvoiceEmail" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="电子发票接收手机" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" v-model="ruleFormData.electronicInvoicePhone" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-tab-pane>
                    <a-tab-pane key="4" tab="银行信息">
                        <a-row>
                            <a-col :span="12">
                                <a-form-item label="开户银行" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" v-model="ruleFormData.openingBank" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="银行账户" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" v-model="ruleFormData.bankAccount" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-tab-pane>
                    <a-tab-pane key="5" tab="联系人信息">
                        <a-row>
                            <a-col :span="12">
                                <a-form-item label="联系人姓名" v-bind="formItemLayout">
                                    <a-input type="text" autocomplete="off" placeholder="请输入联系人姓名" v-model="ruleFormData.contactMan" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="联系人电话" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="false" placeholder="请输入联系人电话" v-model="ruleFormData.contactPhone"></a-input>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item label="联系人地址" v-bind="formItemLayout">
                                    <a-input allowClear type="text" autocomplete="false" placeholder="请输入联系人地址" v-model="ruleFormData.contactAddress"></a-input>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-tab-pane>
                </a-tabs>
            </a-form>
        </a-modal>
    </div>
</template>
<script>
//区域选择
import { treeList } from "@/api/area";
import { areaPageListToTreeForId } from "@/utils/tree";
import { save } from "@/api/erp/partner";

export default {
    props: {
        data: {
            type: Array,
            default: () => [],
        },
    },
    data() {
        return {
            visible: false,
            partnerType: [
                //类型-1:客户，2:供应商，3:客户/供应商
                {
                    type: 1,
                    title: "客户",
                },
                {
                    type: 2,
                    title: "供应商",
                },
                {
                    type: 3,
                    title: "客户/供应商",
                },
            ],
            labelCol: 10,
            wrapperCol: 14,
            //输入框布局
            formItemLayout: {
                labelCol: { span: 10 },
                wrapperCol: { span: 14 },
            },
            areaId: "",
            ruleFormData: {
                address: "",
                areaId: 0, // 省市编码
                areaName: "", // 省市名称
                bankAccount: "", //
                chargeOfficeId: "", // 租户分管部门ID
                chargeOfficeName: "", // 租户分管部门名字
                chargeUserId: "", // 租户分管人员ID
                chargeUserName: "", // 租户分管人员名字
                companyNumber: "", // 往来单位 社会统一代码
                contactAddress: "", // 往来单位联系人地址
                contactMan: "", // 往来单位联系人
                contactPhone: "", //
                creditGrade: "", // 信用等级
                creditLimit: "", // 信用额度
                crmId: "", // 客户ID（往来单位）
                crmName: "", // 往来单位名称
                crmSimpleName: "", // 客户简称
                electronicInvoiceEmail: "",
                electronicInvoicePhone: "",
                fiscalYear: "", // 会计年度
                legalPerson: "", // 法人代表
                openingBank: "",
                partnerType: 1, //往来性质：1:客户，2:供应商，3:客户/供应商
                phone: "", //电话
                phonetic: "", //助记码
                riskLevel: "", // 风险等级
                taxNature: "", // 纳税性质(一般纳税人/小规模税人)
                taxRate: "", // 税率
            },
            //行政区信息
            regions: [],

            //信用等级
            creditRatingArray: [
                {
                    leave: 1,
                    name: "好",
                },
                {
                    leave: 2,
                    name: "中",
                },
                {
                    leave: 3,
                    name: "差",
                },
            ],
            //风险等级
            riskArray: [
                {
                    leave: 1,
                    name: "高",
                },
                {
                    leave: 2,
                    name: "中",
                },
                {
                    leave: 3,
                    name: "低",
                },
            ],
            //纳税性质
            taxNatureList: ["一般纳税人", "小规模税人"],
            //报税地区列表
            taxAreaList: [],
            //是否是零售客户
            retailArray: ["是", "否"],
        };
    },
    beforeCreate() {
        this.form = this.$form.createForm(this, { name: "box" });
    },
    created() {
        this.areaTree();
    },
    methods: {
        showModal() {
            this.visible = true;
        },
        handleCancel() {
            this.visible = false;
        },
        handleAdd() {
            //新增
            this.showModal();
            let { ruleFormData } = this;

            for (const key in ruleFormData) {
                ruleFormData[key] = '';
            }
            this.ruleFormData = ruleFormData;
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        partnerType: this.$form.createFormField({
                            value: "",
                        }),
                        crmName: this.$form.createFormField({
                            value: "",
                        }),
                        areaName: this.$form.createFormField({
                            value: "",
                        }),
                    };
                },
            });
        },
        handleEdit(row, index) {
            //修改数据
            this.showModal();
            this.$nextTick(() => {
                this.ruleFormData = row;
                if (row) {
                    this.form.setFieldsValue({
                        areaName: row.areaName.split("/"),
                        partnerType: row.partnerType,
                        crmName: row.crmName,
                    });
                    row.creditGrade =
                        row.creditGrade == 1 ? "好" : row.creditGrade == 2 ? "中" : "差"; // 信用等级
                    row.riskLevel =
                        row.riskLevel == 1 ? "高" : row.riskLevel == 2 ? "中" : "低"; // 风险等级
                }
            });
        },
        handleOk(e) {
            //提交数据
            e.preventDefault();
            this.form.validateFields((err, values) => {
                //所属区域
                let area = "";
                for (let i = 0; i < values.areaName.length; i++) {
                    if (values.areaName.length - i != 1) {
                        area += values.areaName[i] + "/";
                    } else {
                        area += values.areaName[i];
                    }
                }
                values.areaName = area;
                values.areaId = this.areaId;

                this.ruleFormData.creditGrade = this.ruleFormData.creditGrade;
                this.ruleFormData.riskLevel = this.ruleFormData.riskLevel;


                this.ruleFormData = Object.assign(this.ruleFormData, { ...values });

                console.log("保存的数据：" + this.ruleFormData);
                if (!err) {
                    save(this.ruleFormData).then((response) => {
                        if (response.code === 200) {
                            this.$message.success("保存成功");
                            this.handleCancel(); //关闭弹窗
                            this.$emit("ok");
                        } else {
                        }
                    });
                }
            });
        },
        //加载 区域数据
        areaTree() {
            treeList()
                .then((response) => {
                    if (response.code === 200) {
                        const { data } = response;
                        const childrenNav = [];
                        const province = data.filter((f) => f.parentCode == 0);
                        this.taxAreaList = province;
                        areaPageListToTreeForId(data, childrenNav, 0);
                        console.log("加载 区域数据:", childrenNav);
                        this.regions = childrenNav;
                    }
                })
                .catch((error) => { });
        },
        //地区选择事件
        onAreaChange(value, selectedOptions) {
            this.areaId = selectedOptions.map((o) => o.areaCode)[
                selectedOptions.length - 1
            ];
            // console.log(this.areaText,value,selectedOptions)
        },
    },
};
</script>
<style lang="less">
.input-box {
    .input-title {
        line-height: 32px;
        text-align: right;
        padding-right: 10px;
    }
    .ant-select {
        width: 100%;
    }
    .input-title::after {
        content: " :";
    }
    .ant-col {
        margin-bottom: 10px;
    }
}
.modal-wrapper .ant-form-item-with-help {
    margin-bottom: 0 !important;
}
</style>